﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telecom.Data;

namespace Telecom.Service
{
    public class MainmenuSer
    {
        private readonly EntitiesTelecom dbContext = new EntitiesTelecom();

        public MainmenuSer()
        {
            dbContext.Configuration.LazyLoadingEnabled = false;
            dbContext.Configuration.ProxyCreationEnabled = false;
        }


        public decimal addorUpdate(MAIN_MENU entity)
        {
            if (entity.MMID == 0) dbContext.MAIN_MENU.Add(entity);
            else dbContext.Entry(entity).State = System.Data.EntityState.Modified;
            dbContext.SaveChanges();
            return entity.MMID;
        }

        public List<MAIN_MENU> getList()
        {
            dbContext.Configuration.ProxyCreationEnabled = false;

            try
            {
                return dbContext.MAIN_MENU.OrderBy(p => p.STT).ToList();
            }
            catch
            {
                return null;
            }
        }

        public MAIN_MENU GetById(decimal id)
        {
            try
            {
                return dbContext.MAIN_MENU.Where(p => p.MMID == id).First();
            }
            catch
            {
                return null;
            }
        }

        public MAIN_MENU GetByFIrst()
        {
            try
            {
                return dbContext.MAIN_MENU.OrderBy(p => p.STT).First();
            }
            catch
            {
                return null;
            }
        }

        public bool detele(int id)
        {
            try
            {
                var _entity = GetById(id);

                var listEntity = dbContext.MENUS.Where(p => p.MAINMENU == id).ToList();
                foreach (var item in listEntity)
                {
                    dbContext.MENUS.Remove(item);
                    dbContext.SaveChanges();
                }

                dbContext.MAIN_MENU.Remove(_entity);

                dbContext.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        public List<MAIN_MENU> getListMainMenuForUser(decimal[] rolesid)
        {
            try
            {
                // list Id Menu
                var listIdMenu = dbContext.ROLE_MENUS.Where(p => rolesid.Contains(p.ROLEID.Value)).GroupBy(p => p.MENUID).Select(p => p.Key).ToArray();

                // ds menu
                var listmenu = dbContext.MENUS.Where(p => listIdMenu.Contains(p.MENUID)).GroupBy(p => p.MAINMENU).Select(p => p.Key).ToArray();

                return dbContext.MAIN_MENU.Where(p => listmenu.Contains(p.MMID)).OrderBy(l => l.STT).ToList();
            }
            catch { return null; }

        }
    }
}
